#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/wait.h>
#include<unistd.h>
#include <fcntl.h>
#include<sys/socket.h>
#include<sys/stat.h>
#include<arpa/inet.h>
#include<event2/event.h>
#include<event2/listener.h>
#include<event2/bufferevent.h>
#define SERVICE_PORT 9527
//需求使用event库实现tcp模型服务器

//读函数
void read_bc(struct bufferevent*buffevent,void*arg){
      char buf[1024];
      bufferevent_read(buffevent,buf,sizeof(buf));//buffevent里面包含了文件描述符
      printf("buf : %s\n",buf);
      char*p="接收到数据\n";
      bufferevent_write(buffevent,p,strlen(p)+1);
      sleep(1);
}

//evconnlistener_new_bind函数回调默认参数
//void (*evconnlistener_cb)(struct evconnlistener*listener,evutil_socket_t fd,struct sockaddr*addr,int len,void*ptr)
 void listener_cb(struct evconnlistener*listener,evutil_socket_t fd,struct sockaddr*addr,int len,void*ptr){
      printf("连接到新的客户端\n");
      //创建事件
      struct event_base*base=(struct event_base*)ptr;
      struct bufferevent*buffevent;
      buffevent=bufferevent_socket_new(base,fd,BEV_OPT_CLOSE_ON_FREE);

      //将事件设置回调函数（读函数）
      bufferevent_setcb(buffevent,read_bc,NULL,NULL,NULL);

      //启动读事件
      bufferevent_enable(buffevent,EV_READ);
 }
int main(){
    struct event_base*base=event_base_new();
    struct sockaddr_in saddr;
    saddr.sin_family=AF_INET;
    saddr.sin_port=htons(SERVICE_PORT);
    saddr.sin_addr.s_addr=htonl(INADDR_ANY);
    
    //绑定bind 监听listen 创建socket  连接ccept
    struct evconnlistener*listenever=evconnlistener_new_bind(base,listener_cb,
                                                             base,LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE,
                                                             20,(struct sockaddr*)&saddr,sizeof(saddr));
    
    //启动循环监听
    event_base_dispatch(base);

    //释放
    event_base_free(base);
    evconnlistener_free(listenever);

    return 0;
}